﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Ease.EaseDialog.Runtime.Data;
using Ease.EaseDialog.Runtime.DataAgent;
using Sirenix.OdinInspector;
using Unity.VisualScripting;
using UnityEngine;

namespace Ease.EaseDialog.Runtime
{
    public class DialogManager : MonoBehaviour
    {
        public DialogDataSo so;

        public List<BaseDialogData> datas = new List<BaseDialogData>();

        [Button]
        public void StartDialog()
        {
            datas.Clear();
            datas.AddRange(so.datas);
            StartCoroutine(CoStartDialog());
        }

        IEnumerator CoStartDialog()
        {
            //找到下一个
            BaseDialogDataAgent agent = GetNewAgent();
            while (agent != null)
            {
                bool isOver = false;
                //开始
                agent.Start(() => { isOver = true; });
                //等待结束.
                yield return new WaitUntil(() => isOver);
                yield return new WaitForSeconds(2f);
                //继续获取。
                agent = GetNewAgent();
            }
            Debug.LogError("全部结束");
            //全部结束。
            yield break;
        }

        private BaseDialogDataAgent GetNewAgent()
        {
            if (datas.Count == 0)
                return null;
            var agnent =  datas.FirstOrDefault().CreateAgent() as BaseDialogDataAgent;
            datas.RemoveAt(0);
            return agnent;
        }
    }
}